﻿

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Transactions;
using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Modules.Clinicom.CCPatient.DAL;

namespace P2.Cuberry.Modules.Clinicom.CCPatient.BusinessEntities
{
    class CCPatientVisit : BizObject, INotifyPropertyChanged
    {

        #region Constructors
        
        public CCPatientVisit()
        {
            Modified = false;
        }


        public CCPatientVisit(DAL.CCPatientVisit ccPatientVisit)
        {
            Load(ccPatientVisit);
        }

        #endregion


        #region Members

        //++KeyID
        int _visitID = -1;
        public int VisitID
        {
            get { return _visitID; }
            protected set
            {
                if (_visitID != value)
                {
                    _visitID = value;
                    Modified = true;
                }
            }
        }


        int _patientID = -1;
        public int PatientID
        {
            get { return _patientID; }
            protected set
            {
                if (_patientID != value)
                {
                    _patientID = value;
                    Modified = true;
                }
            }
        }

        //Add++
        DateTime? _openingTime = DateTime.Now;
        public DateTime? OpeningTime
        {
            get { return _openingTime; }
            set
            {
                if (value != _openingTime)
                {
                    _openingTime = value;
                    Modified = true;
                }
            }
        }

        DateTime? _closingTime = DateTime.Now;
        public DateTime? ClosingTime
        {
            get { return _closingTime; }
            set
            {
                if (value != _closingTime)
                {
                    _closingTime = value;
                    Modified = true;
                }
            }
        }

        string _leavingStatus = String.Empty;
        public string LeavingStatus
        {
            get { return _leavingStatus; }
            set
            {
                if (value != _leavingStatus)
                {
                    _leavingStatus = value;
                    Modified = true;
                }
            }
        }

        string _closedBy = String.Empty;
        public string ClosedBy
        {
            get { return _closedBy; }
            set
            {
                if (value != _closedBy)
                {
                    _closedBy = value;
                    Modified = true;
                }
            }
        }

        string _diagnosis = String.Empty;
        public string Diagnosis
        {
            get { return _diagnosis; }
            set
            {
                if (value != _diagnosis)
                {
                    _diagnosis = value;
                    Modified = true;
                }
            }
        }

        string _therapyDuration = String.Empty;
        public string TherapyDuration
        {
            get { return _therapyDuration; }
            set
            {
                if (value != _therapyDuration)
                {
                    _therapyDuration = value;
                    Modified = true;
                }
            }
        }

        string _note = String.Empty;
        public string Note
        {
            get { return _note; }
            set
            {
                if (value != _note)
                {
                    _note = value;
                    Modified = true;
                }
            }
        }


        public CCPatient ParentCCPatient { set; get; }

    #endregion


        #region Read operations

        public void Load(DAL.CCPatientVisit ccPatientVisit)
        {
            try
            {
                if (ccPatientVisit != null)
                {
                    this.VisitID = ccPatientVisit.VisitID;
                    this.PatientID = ccPatientVisit.PatientID;
                    this.OpeningTime = ccPatientVisit.OpeningTime;
                    this.ClosingTime = ccPatientVisit.ClosingTime;
                    this.LeavingStatus = ccPatientVisit.LeavingStatus;
                    this.ClosedBy = ccPatientVisit.ClosedBy;
                    this.Diagnosis = ccPatientVisit.Diagnosis;
                    this.TherapyDuration = ccPatientVisit.TherapyDuration;
                    this.Note = ccPatientVisit.Note;

                    this.StatusID = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID;
                    this.Timestamp = ccPatientVisit.TStamp;
                }
                else
                {
                    this.VisitID = -1;
                    this.PatientID = -1;
                    this.OpeningTime = null;
                    this.ClosingTime = null;
                    this.LeavingStatus = "";
                    this.ClosedBy = null;
                    this.Diagnosis = "";
                    this.TherapyDuration = "";
                    this.Note = "";
                    P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                    this.StatusID = initStatus.StatusID;
                }
                Modified = false;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        protected P2TransactionMessage FillMyObject()
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();

            try
            {
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (CCPatientDataContext db = new CCPatientDataContext(connectionString))
                {
                    var patientVisits = from tran in db.CCPatientVisit
                                       where tran.VisitID  == this._visitID 
                                       select tran;
                    if (patientVisits.Count() > 0)
                    {
                        foreach (var patientVisit in patientVisits)
                        {
                            Load(patientVisit);
                        }
                    }
                }

                tMsg.TransactionStatus = "green";
                tMsg.MessageText = "TMsg_FillMyObjectSuceeded";
            }
            catch (Exception ex) //AM:TC!!
            {
                tMsg.TransactionStatus = "red";
                tMsg.MessageText = "Error_Error";
                tMsg.MessageFreeText = ex.Message;
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }

            this.MessageStack.Add(tMsg);
            return tMsg;
        }


        public static ObservableCollection<CCPatientVisit> GetCCPatitentVistsForPatient(CCPatient ccPatient, PropertyChangedEventHandler onChange)
        {
            try
            {
                ObservableCollection<CCPatientVisit> itemsCollection = new ObservableCollection<CCPatientVisit>();

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (CCPatientDataContext db = new CCPatientDataContext(connectionString))
                {
                    var ccPatientVisits = from ccPatientVisit in db.CCPatientVisit
                                       where ccPatientVisit.PatientID == ccPatient.PatientID
                                       select ccPatientVisit;
                    if (ccPatientVisits.Count() > 0)
                    {
                        foreach (var xccPatientVisit in ccPatientVisits)
                        {
                            itemsCollection.Add(new CCPatientVisit(xccPatientVisit) { ParentCCPatient = ccPatient });
                        }
                    }
                }

                return itemsCollection;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "CCPatientVisit", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        #endregion


        #region Update operations

        public P2MessageStack InsertAndUpdate(CCPatientDataContext db)
        {
            P2MessageStack MessageStack = new P2MessageStack();

            try
            {
                if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = User.Current.UserID;
                this.EditedBy = User.Current.UserID;
                DAL.CCPatientVisit editedItem;
                if (this.VisitID < 0)
                {
                    editedItem = new DAL.CCPatientVisit()
                    {                        
                        PatientID = this.PatientID,
                        OpeningTime = this.OpeningTime,
                        ClosingTime = this.ClosingTime,
                        LeavingStatus = this.LeavingStatus,                        
                        ClosedBy = this.ClosedBy,
                        Diagnosis = this.Diagnosis,
                        TherapyDuration = this.TherapyDuration,
                        Note = this.Note,

                        CreatedBy = this.CreatedBy,
                        CreatedOn = DateTime.Now,
                        EditedBy = this.EditedBy,
                        EditedOn = DateTime.Now
                    };
                    db.AddToCCPatientVisit(editedItem);
                }
                else
                {
                    editedItem = (from ti in db.CCPatientVisit
                                  where ti.VisitID == this.VisitID
                                  select ti).First();
                    if (editedItem.TStamp == this.Timestamp)
                    {                        
                        editedItem.PatientID = this.PatientID;
                        editedItem.OpeningTime = this.OpeningTime;
                        editedItem.ClosingTime = this.ClosingTime;
                        editedItem.LeavingStatus = this.LeavingStatus;
                        editedItem.ClosedBy = this.ClosedBy;
                        editedItem.Diagnosis = this.Diagnosis;
                        editedItem.TherapyDuration = this.TherapyDuration;
                        editedItem.Note = this.Note;

                        editedItem.EditedBy = this.EditedBy;
                        editedItem.EditedOn = DateTime.Now;
                    }
                    else
                    {
                        MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("TMsg_PaymentNotUpdated")));
                    }
                }
            }
            catch (Exception ex) //AM:TC!!
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
            return MessageStack;
        }


        public void Delete(CCPatientDataContext db)
        {
            if (this.VisitID > 0)
            {
                var item = (from ti in db.CCPatientVisit
                            where this.VisitID == ti.VisitID 
                            select ti).First();
                db.DeleteObject(item);
                db.SaveChanges();
            }
        }

        #endregion


        #region Copy Operations

        public CCPatientVisit GetCopy()
        {
            try
            {
                CCPatientVisit newItem = new CCPatientVisit();
                newItem.PatientID = this.PatientID;
                newItem.VisitID = this.VisitID;
                newItem.OpeningTime = this.OpeningTime;
                newItem.ClosingTime = this.ClosingTime;
                newItem.LeavingStatus = this.LeavingStatus;
                newItem.ClosedBy = this.ClosedBy;
                newItem.Diagnosis = this.Diagnosis;
                newItem.TherapyDuration = this.TherapyDuration;
                newItem.Note = this.Note;

                newItem.Timestamp = this.Timestamp;
                newItem.Modified = this.Modified;
                return newItem;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }


        public void UpdateFrom(CCPatientVisit sourceItem)
        {
            try
            {
                this.PatientID = sourceItem.PatientID;
                this.VisitID = sourceItem.VisitID;
                this.OpeningTime = sourceItem.OpeningTime;
                this.ClosingTime = sourceItem.ClosingTime;
                this.LeavingStatus = sourceItem.LeavingStatus;
                this.ClosedBy = sourceItem.ClosedBy;
                this.Diagnosis = sourceItem.Diagnosis;
                this.TherapyDuration = sourceItem.TherapyDuration;
                this.Note = sourceItem.Note;

                this.Timestamp = sourceItem.Timestamp;
                this.Modified = sourceItem.Modified;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion


        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }


        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("VisitID");
            OnPropertyChanged("OpeningTime");
            OnPropertyChanged("ClosingTime");
            OnPropertyChanged("LeavingStatus");
            OnPropertyChanged("ClosedBy");
            OnPropertyChanged("Diagnosis");
            OnPropertyChanged("TherapyDuration");
            OnPropertyChanged("Note");
        }

        #endregion


        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                {
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "VisitID", this);

                    _validator.PropertyValidators.Add(new P2ValidationItemDateTime()
                    {
                        ClassName = "CCPatientVisit",
                        Mandatory = true,
                        ValidationType = P2ValidationStatus.red,
                        MinValue = DateTime.MinValue,
                        MaxValue = DateTime.MaxValue,
                        PropertyName = "OpeningTime"
                    });
                }
                return _validator;
            }
        }

        #endregion
    }
}
